import os

from django.shortcuts import get_object_or_404, render_to_response
from django.http import HttpResponseRedirect, Http404, HttpResponse, HttpResponseNotFound
from django.template import RequestContext
from django.utils import simplejson

import tempfile

from damn import GetManagers
from damn.analyzer import AnalyzerException
from assets.uploadhelper import *

def upload(request): 
  request.session['UploadedFiles'] = {}
  return render_to_response('upload.html', {}, context_instance=RequestContext(request))

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def ajax_upload( request ):
  if request.method == "POST":   
    try:
      # save the file
      upload, filename, is_raw = get_upload(request)
      success, destination = save_upload( upload, filename, is_raw )
      # let Ajax Upload know whether we saved it or not
      fileRef = GetManagers()['Analyzer'].AnalyzeFile(destination)
      ret_json = simplejson.dumps({ 'success': success, 'fileRef': fileRef.serialize(), })
      request.session['UploadedFiles'][fileRef.hash] = fileRef
      request.session.set_expiry(0)
    except AnalyzerException as e:
      ret_json = simplejson.dumps({ 'success': False, 'error': e.msg, })
    except:
      import sys
      ret_json = simplejson.dumps({ 'success': False, 'error': str([repr(x) for x in sys.exc_info()]), })
    return HttpResponse( ret_json )


def transcode( request, hash, subName, format): 
  trans = GetManagers()['Transcoder']
  args = {}
  noCache = False
  for k,v in request.GET.items():
    if k == 'noCache':
      noCache = True
    elif not k == 'format':
      args[str(k)] = v
    
  fileRef = request.session.get('UploadedFiles', {}).get(hash, None)
  if not fileRef:
    raise Http404("You haven't uploaded a file yet! "+str(request.session.get('UploadedFiles', {})))    
  asset = fileRef.GetAsset(subName, format)
  if not asset:
    raise Http404("No such asset in file")
  
  if noCache:
    path = trans.transcode(asset, 'image/jpeg', **args) 
  else:  
    path, created = trans.get_or_transcode(asset, 'image/jpeg', **args)   
  try:
    f = open(path, 'rb')
    data = f.read()
    f.close()
    response = HttpResponse(data, mimetype='image/jpeg')
    response['Content-Length'] = str(len(data))
    response['Access-Control-Allow-Origin'] = '*'
    return response
  except IOError:
    return HttpResponseNotFound("IOError for %s"%(path))

def assets_exclude(request, hash, subName, format):
  files = request.session.get('UploadedFiles', {}).values()
  assets = []
  for file in files:
    if file.hash == hash:
      for a in file.assets:
        if not a.subName == subName and not a.format == format:
          assets.append(a)
    else:
      assets.extend(file.assets)
  ret_json = simplejson.dumps([ass.serialize(False, False) for ass in assets if not ass.brokenReference])
  return HttpResponse( ret_json ) 


def asset(request, hash, subName, format):
  fileRef = request.session.get('UploadedFiles', {}).get(hash, None)
  if not fileRef:
    raise Http404("You haven't uploaded a file yet!") 
  asset = fileRef.GetAsset(subName, format)
  if not asset:
    raise Http404("No such asset in file")
    
  ret_json = simplejson.dumps(asset.serialize())
  return HttpResponse( ret_json ) 


def files(request):
  files = request.session.get('UploadedFiles', {}).values()
  ret_json = simplejson.dumps([f.serialize() for f in files if not f.brokenReference])
  return HttpResponse( ret_json ) 
  
  
def relink( request ):
  if request.method == "POST":  
    srcChecksum = request.POST['srchash']
    srcSubName = request.POST['srcSubName']
    srcFormat = request.POST['srcFormat']
    
    depChecksum = request.POST['dephash']
    depSubName = request.POST['depSubName']
    depFormat = request.POST['depFormat']
     
    newDepChecksum = request.POST['newDephash']
    newDepSubName = request.POST['newDepSubName']
    newDepFormat = request.POST['newDepFormat']

    srcf = request.session.get('UploadedFiles', {}).get(srcChecksum, None)
    if not srcf: raise Http404("No such srcf in files")
    newDepf = request.session.get('UploadedFiles', {}).get(newDepChecksum, None)
    if not newDepf: raise Http404("No such newDepf in files")
    
    src = srcf.GetAsset(srcSubName, srcFormat)
    if not src: raise Http404("No such src in assets")
    newDep = newDepf.GetAsset(newDepSubName, newDepFormat)
    if not newDep: raise Http404("No such newDep in assets")
    
    for i, dep in enumerate(src.dependencies):
      if dep.file.fileName == depChecksum: #fileName cause dependency is a brokenReference
        if dep.subName == depSubName and dep.format == depFormat:
          src.dependencies[i] = newDep
    
    #Update the session data
    request.session['UploadedFiles'][srcf.hash] = srcf
    request.session.set_expiry(0)
    
    return HttpResponse()  
    
    
